﻿using Confluent.Kafka;
using Common.Json;
using Common.MQ;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Common.Kafka
{
    /// <summary>
    /// kafka生产者
    /// </summary>
    public class KafkaProducer : IMQProducer
    {
        /// <summary>
        /// Producer
        /// </summary>
        private IProducer<Null, string> _producer;
        private readonly KafkaSetting setting;
        /// <summary>
        /// kafka生产者
        /// </summary>
        /// <param name="setting"></param>
        public KafkaProducer(KafkaSetting setting)
        {
            this.setting = setting;
        }
        /// <summary>
        /// Kafka producer 初始化 
        /// </summary>
        private void Init()
        {
            if (_producer == null)
            {
                var config = new ProducerConfig
                {
                    BootstrapServers = setting.Broker
                };
                _producer = new ProducerBuilder<Null, string>(config).Build();
            }
        }
        /// <inheritdoc/>
        void IMQProducer.Declare(IDestination queue)
        {
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task<bool> ProduceAsync(IMessageModel message)
        {
            Init();
            string json = message.GetMessageJson();
            await _producer.ProduceAsync(message.GetDestination(), new Message<Null, string> { Value = json });
            return true;
        }
        /// <summary>
        /// 直接发送Data数据到kafka
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="destination"></param>
        /// <returns></returns>
        public Task<bool> ProduceAsync<T>(T data, string destination)
        {
            Init();
            var message = new MessageModel<T>(destination, data);
            return this.ProduceAsync(message);
        }

        Task<bool> IMQProducer.ProduceAsync<T>(T data, string destination, MessageProperty property)
        {
            return ProduceAsync(data, destination);
        }
    }
}
